﻿using UnityEngine;
using System.Collections;
using Newtonsoft.Json;
using System.Threading;

public class CodecFactory
{

    public static byte[] EncodeMessage(IGameMessage request)
    {
        GameMessageHeader header = request.GetHeader();
        int totalSize = GameMessageHeader.HEADER_LENGTH + 4;

        byte[] bodyBytes = request.Write();
        int compress = 0;
        if (bodyBytes != null)
        {
            totalSize += bodyBytes.Length;
            totalSize += 1;//压缩标记位所占字节长度
            //TODO 添加包体是否压缩的判断
            if (bodyBytes.Length > GameClientConfig.CompressSize)
            {
                compress = 1;
                //TODO 对消息进行压缩
            }
        }

        ByteBuf byteBuf = new ByteBuf(totalSize);
        byteBuf.WriteInt(totalSize);
        header.Write(byteBuf);
        if (bodyBytes != null)
        {
            byteBuf.WriteByte(compress);
            byteBuf.WriteBytes(bodyBytes);
        }
        return byteBuf.ToArray();
    }

    public static void DecodeMessage(ByteBuf byteBuf, IGameMessage gameMessage)
    {
        gameMessage.GetHeader().Read(byteBuf);
        if (byteBuf.IsReadable())
        {
            int compress = byteBuf.ReadByte();
            int size = byteBuf.ReadableBytes();
            byte[] bytes = new byte[size];
            byteBuf.ReadBytes(bytes);
            if (compress == 1)
            {
                //TODO 服务器对数据进行了压缩，这里要进行一下解压缩

            }
            gameMessage.Read(bytes);
            Debug.Log("接收消息:" + gameMessage.GetHeader().ClientSeqID + "，" + gameMessage.GetHeader().MessageId);
        }

    }
}
